<template>
  <div :id="id" :style="style" />
</template>

<script>
import { debounce } from '@/utils';
export default {
    name: 'Charts',
    props: {
        id: {
            type: String
        },
        width: {
            type: String,
            default: '100%'
        },
        height: {
            type: String,
            default: '100%'
        },
        autoResize: {
        type: Boolean,
        default: true
        },
        option: {
            type: Object,
            default() {
                return {
                    title: {
                        text: 'ECharts 入门示例',
                        textStyle: {
                            color: '#fff',
                            fontSize: '12px'
                        }
                    },
                    tooltip: {},
                    legend: {
                        data: ['销量'],
                        textStyle: {
                            fontSize: 12,
                            color: '#fff'
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [{
                        data: [820, 932, 901, 934, 1290, 1330, 1320],
                        type: 'line'
                    }]
                }
            }
        }
    },
    data() {
        return {
            chart: ''
        }
    },
    computed: {
        style() {
            return {
                width: this.width,
                height: this.height
            }
        }
    },
    watch: {
        option: {
            handler(newVal, oldVal) {
                if (this.chart) {
                    this.chart.resize()
                    this.chart.setOption(newVal, true)
                } else {
                    this.init()
                }
            },
            deep: true,
        },
        style: {
            handler(newVal, oldVal) {
                console.log(oldVal)
                console.log(newVal)
            }
        }
    },
    mounted() {
        this.init();
        if (this.autoResize) {
        this.__resizeHanlder = debounce(() => {
          if (this.chart) {
            this.chart.resize()
          }
        }, 100);
        window.addEventListener('resize', this.__resizeHanlder)
      }
    },
    methods: {
        init() {
            let that = this;
            this.chart = this.$echarts.init(document.getElementById(this.id))
           // this.chart.resize()
            this.chart.setOption(this.option, true)
           // window.addEventListener('resize', this.chart.resize)
           
        }
    }
}
</script>
